package samsung.sds.survey.surveyStatistics.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import samsung.sds.survey.surveyStatistics.dao.QualitySurveyStatisticsMapper;
import samsung.sds.survey.surveyStatistics.model.QualitySurveyStatisticsResultEntity;
import samsung.sds.survey.surveyStatistics.model.SurveyResultEntity;
import samsung.sds.survey.surveyStatistics.service.QualitySurveyStatisticsService;
import samsung.sds.system.common.baseQuery.AbstractBaseService;
import samsung.sds.system.common.baseQuery.model.PageData;
import samsung.sds.system.common.model.QueryParam;
import samsung.sds.system.export.service.ExportService;
import samsung.sds.system.export.service.ExportServiceImpl;
import samsung.sds.survey.surveyManagement.model.SurveyEntity;
import samsung.sds.survey.surveyManagement.service.SurveyManagementService;

/**
 * @author dan5.li
 * @createDate 2016-02-15
 * 数字类型问卷调查统计
 */
@Service
public class QualitySurveyStatisticsServiceImpl extends AbstractBaseService<QualitySurveyStatisticsResultEntity> 
	implements QualitySurveyStatisticsService {

	private static final Logger log = Logger
			.getLogger(QualitySurveyStatisticsServiceImpl.class);
	@Autowired
	private QualitySurveyStatisticsMapper qualitySurveyStatisticsMapper;
	@Autowired
	private SurveyManagementService surveyManagementServiceImpl;
	@Autowired
	private ExportService exportServiceImpl;
	
	protected QualitySurveyStatisticsMapper getMapper() {
		return qualitySurveyStatisticsMapper;
	}

	/**
	 * 根据调查ID获取所有问题列表
	 * 
	 * @param survey_Id
	 * @return
	 */
	public List<QualitySurveyStatisticsResultEntity> getSurveyQuestion(
			String survey_Id) {
		return qualitySurveyStatisticsMapper.selectTF_F_QUESTION(survey_Id);
	}

	/**
	 * 获取调查结果列表
	 * 
	 * @param survey_Id
	 * @return
	 */
	public List<QualitySurveyStatisticsResultEntity> getStatisticsList(
			QueryParam param) {
		return qualitySurveyStatisticsMapper.queryList(param);
	}

	/**
	 * 根据分页参数分页获取调查结果列表
	 * 
	 * @param param
	 * @return
	 */
	public PageData<QualitySurveyStatisticsResultEntity> getStatisticsPageList(
			QueryParam param) {
		// 获取回答该问卷的用户列表
		List<QualitySurveyStatisticsResultEntity> voteUserList = qualitySurveyStatisticsMapper
				.queryListPage(param);
		for (QualitySurveyStatisticsResultEntity voteUser : voteUserList) {
			// 问卷ID
			String surveyId = voteUser.getSurvey_id();
			// 用户名
			String userName = voteUser.getUsername();
			// 获取该用户的答案列表
			List<SurveyResultEntity> answers = qualitySurveyStatisticsMapper
					.selectTF_F_SURVEY_RESULT02(surveyId, userName);
			// 设置结果列表到回答用户
			voteUser.setAnswers(answers);
			// 获取时间
			QualitySurveyStatisticsResultEntity result = qualitySurveyStatisticsMapper
					.selectTF_F_SURVEY_RESULT01(surveyId, userName);
			// 设置投票时间 如果没有修改时间，则时间按照创建时间
			if (result != null) {
				String lastModifyTime = result.getLast_Modify_Time();
				voteUser.setLast_Modify_Time(lastModifyTime);
			} else {
				voteUser.setLast_Modify_Time("N/A");
			}
		}

		// 排序
		for (int i = 0; i < voteUserList.size() - 1; i++) {
			for (int j = 1; j < voteUserList.size() - i; j++) {
				String time = voteUserList.get(j - 1).getLast_Modify_Time();
				String lastTime = voteUserList.get(j).getLast_Modify_Time();
				if (time.compareTo(lastTime) > 0) {
					QualitySurveyStatisticsResultEntity entity = voteUserList
							.get(j - 1);
					voteUserList.set(j - 1, voteUserList.get(j));
					voteUserList.set(j, entity);
				}
			}
		}
		PageData<QualitySurveyStatisticsResultEntity> pageData = new PageData<QualitySurveyStatisticsResultEntity>();
		pageData.setQueryResult(voteUserList);
		pageData.setQueryParam(param);
		return pageData;
	}

	/**
	 * 根据调查问卷ID和用户名获取投票时间
	 * 
	 * @param surveyId
	 * @param userName
	 * @return
	 */
	public QualitySurveyStatisticsResultEntity getVoteTime(String surveyId,
			String userName) {
		QualitySurveyStatisticsResultEntity result = qualitySurveyStatisticsMapper
				.selectTF_F_SURVEY_RESULT01(surveyId, userName);
		return result;
	}
	
	/**
	 * 导出
	 * 
	 * @param request
	 * @param response
	 * @param surveyId
	 * @param map
	 * @throws IOException
	 */
	public void qualitySurveyStatisticsExport(HttpServletRequest request,
			HttpServletResponse response, String surveyId,
			Map<String, Object> map) throws IOException {

		// 问卷ID类型转换
		String id = surveyId;
		// 获取问题列表
		List<QualitySurveyStatisticsResultEntity> questionList = getSurveyQuestion(id);
		// 获取投票结果列表
		Map<String, Object> queryMap = new HashMap<String, Object>();
		// 查询条件 调查表ID
		queryMap.put("surveyId", id);
		// 实体封装查询参数
		QueryParam queryParam = new QueryParam();
		// 设置查询条件
		queryParam.setQueryCondition(queryMap);
		List<QualitySurveyStatisticsResultEntity> voteResultList = getStatisticsList(queryParam);
		// 获取投票时间
		for (QualitySurveyStatisticsResultEntity voteResult : voteResultList) {
			QualitySurveyStatisticsResultEntity result = getVoteTime(voteResult.getSurvey_id(),
							voteResult.getUsername());
			if (result != null) {
				voteResult.setLast_Modify_Time(result.getLast_Modify_Time());
			} else {
				voteResult.setLast_Modify_Time("N/A");
			}
		}
		// 导出
		String fileName = null;
		OutputStream os = null;
		FileInputStream fis = null;
		log.info("==== >>>> start export quality survey result");
		try {
			fileName = exportServiceImpl.createExcelForQualitySurvey(map,
					questionList, voteResultList);
			long l = System.currentTimeMillis();
			response.setHeader(
					"content-disposition",
					"attachment;filename="
							+ ExportServiceImpl.toUtf8String(
									map.get("survey_name") + "_" + l, request));
			response.setContentType("application/vnd.ms-excel");// 此项内容随文件类型而异
			byte temp[] = new byte[1000];
			fis = new FileInputStream(fileName);
			int n = 0;
			os = response.getOutputStream();
			while ((n = fis.read(temp)) != -1) {
				os.write(temp, 0, n);
			}
		} catch (Exception e) {
			log.error("error occured when export voted user data");
			e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
			if (new File(fileName).exists()) {
				new File(fileName).delete();
			}
		}
	}


	/**
	 * 获取调查问卷信息
	 * 
	 * @param survey_Id
	 * @return
	 */
	public Map<String, Object> getSurveyMessage(String survey_Id) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		SurveyEntity surveyInfo = surveyManagementServiceImpl.getSurveyInfo(survey_Id);
		// 问卷id
		map.put("survey_id", surveyInfo.getSurvey_Id());
		// 问卷名称
		map.put("survey_name", surveyInfo.getSurvey_Name());
		// 邀请人数
		map.put("ask_num", surveyInfo.getAsk_num());
		// 投票人数
		map.put("vote_num", surveyInfo.getVote_num());
		// 截止时间
		map.put("end_time", surveyInfo.getEnd_Date());
		// 生成时间
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date createDate = new Date();
		map.put("create_date", format.format(createDate));
		return map;
	}

}
